//
//  SaleRecordVC.swift
//  物料商行
//
//  Created by HaoDong Hong on 2017/9/21.
//  Copyright © 2017年 HaoDong Hong. All rights reserved.
//

import UIKit
import SVProgressHUD

class SaleRecordVC: RecordBaseVC, UITableViewDelegate, UITableViewDataSource {
    
    @IBOutlet weak var tableView: UITableView!
    var records = [SaleRecord]()
    var input = SaleRoot()
    let helper = MaterialHelper()
    var currentPage = 1

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.contentInset = UIEdgeInsetsMake(44, 0, 44, 0)
        tableView.register(UINib(nibName: "SaleRecordCell", bundle: nil), forCellReuseIdentifier: "SaleRecordCell")
        input.materialId = materialId
        input.dateType = 1
        requestRecords()
    }
    private func requestRecords() {
        currentPage = 1
        input.page = 1
        SVProgressHUD.show()
        let encoder = JSONEncoder()
        let data = try! encoder.encode(input)
        helper.getSaleRecord(with: data) { (error, records) in
            guard error == nil else {
                SVProgressHUD.showError(withStatus: error.debugDescription)
                SVProgressHUD.dismiss(withDelay: 1.5)
                return
            }
            print(records!.count)
            self.records = records!
            self.tableView.reloadData()
            SVProgressHUD.showSuccess(withStatus: "成功！")
            SVProgressHUD.dismiss(withDelay: 1.5)
        }
    }
    private func handleBtTapped(with tag: Int) {
        input.dateType = tag
        if tag == 4 { //custom date
            showDatePicker()
        } else {
            requestRecords()
        }
    }
    override func alertDoneBtTapped(_ button: UIButton!) {
        guard fromDate != nil && toDate != nil else {
            dateAlert.hideView()
            return
        }
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        input.beginDate = formatter.string(from: fromDate)
        input.endDate = formatter.string(from: toDate)
        dateAlert.hideView()
        requestRecords()
    }
    @IBAction func bottomBtTapped(_ sender: UIButton) {
        handleBtTapped(with: sender.tag)
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SaleRecordCell") as! SaleRecordCell
        let row = indexPath.row
        cell.phoneLabel.text = records[row].record.buyerPhone
        cell.dateLabel.text = records[row].record.created_at
        var price: Double = 0
        var number: Double = 0
        for detail in records[row].detail {
            price = price + Double(detail.number)! * Double(detail.price)!
            number = number + Double(detail.number)!
        }
        cell.priceLabel.text = "\(price)"
        cell.numberLabel.text = "\(number)"
        cell.kindLabel.text = "商户交易"
        cell.selectionStyle = .none
        return cell
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return records.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 66
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let detailVC = SaleRecordDetailVC()
        detailVC.detail = records[indexPath.row].detail
        navigationController?.pushViewController(detailVC, animated: true)
    }
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        /// 因为每一页只有15条信息流
        if indexPath.row == records.count - 1 && (indexPath.row+1) % 15 == 0 {
            currentPage += 1
            SVProgressHUD.show()
            updateRecords()
        }
    }
    
    /// 滑到最下面是刷新数据，并添加到信息流中
    func updateRecords() {
        input.page = currentPage
        let encoder = JSONEncoder()
        let data = try! encoder.encode(input)
        helper.getSaleRecord(with: data) { (error, records) in
            guard error == nil else {
                SVProgressHUD.showError(withStatus: error.debugDescription)
                SVProgressHUD.dismiss(withDelay: 1.5)
                return
            }
            
            for index in 0 ..< records!.count {
                self.records.append(records![index])
                self.tableView.beginUpdates()
                self.tableView.insertRows(at: [IndexPath(row: self.records.count-1, section: 0)], with: .automatic)
                self.tableView.endUpdates()
            }
            SVProgressHUD.dismiss(withDelay: 1.5)
        }
    }
}
